package format

import (
	"fmt"
	"operator/pkg/util"
	"strconv"
	"sync"
	"time"
)

const space = "     "

var mu sync.RWMutex
var formats []Format
var index = 0

type Format struct {
	Id       int    `json:"id"`
	FileName string `json:"file_name"`
	Rows     int    `json:"rows"`
	Error    string `json:"error"`
	Info     string `json:"info"`
	Time     string `json:"time"`
	Type     string `json:"type"`
}

func Println(fn string, rows int, args ...string) {
	mu.Lock()
	index++
	mu.Unlock()
	newf := Format{}
	str := ""
	for _, i := range args {
		str += i
	}
	newf.FileName = fn
	newf.Id = index
	newf.Error = str
	newf.Rows = rows
	newf.Time = time.Now().Format("2006-01-02 15:04:05")
	newf.Type = "info"

	pstr := ""
	pstr += tostring(newf.Id)
	pstr += tostring(newf.FileName)
	pstr += tostring(newf.Rows)
	pstr += tostring(newf.Error)
	pstr += tostring(newf.Info)
	pstr += tostring(newf.Time)
	pstr += tostring(newf.Type, true)

	fmt.Println(pstr)
	formats = append(formats, newf)
}

func Errors(fn string, rows int, args ...string) {
	mu.Lock()
	index++
	mu.Unlock()
	newf := Format{}
	str := ""
	for _, i := range args {
		str += i
	}
	newf.FileName = fn
	newf.Id = index
	newf.Error = str
	newf.Rows = rows
	newf.Time = time.Now().Format("2006-01-02 15:04:05")
	newf.Type = "error"

	pstr := ""
	pstr += tostring(newf.Id)
	pstr += tostring(newf.FileName)
	pstr += tostring(newf.Rows)
	pstr += tostring(newf.Error)
	pstr += tostring(newf.Info)
	pstr += tostring(newf.Time)
	pstr += tostring(newf.Type, true)

	fmt.Println(pstr)
	formats = append(formats, newf)
}

func ShowDetail(id int) {
	if id > len(formats) {
		return
	}
	str := util.JsonEncode(formats[id-1])
	fmt.Println(str)
}

func PrintTitle() {
	str := "ID  %s文件名 %s所在行 %s错误信息%s其他信息%s执行时间%s数据类型\n"

	fmt.Print(fmt.Sprintf(str, space, space, space, space, space, space))
}

func tostring(data interface{}, last ...bool) string {
	result := ""
	switch data.(type) {
	case int:
		result = strconv.Itoa(data.(int))
	case string:
		result = data.(string)
	case time.Time:
		result = data.(time.Time).Format("2006-01-02 15:04:05")
	}
	//if len(result) > 30 {
	//	return result[:30]
	//}
	//if len(last) == 0 {
	//	result += fmt.Sprintf("%s", space)
	//}

	return result
}

func NewFormat(fn string) *Format {
	return &Format{
		FileName: fn,
	}
}

func init() {
	formats = make([]Format, 0, 100)
	mu = sync.RWMutex{}
}
